import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableModel;

import java.awt.event.*;

public class AdminProfileForm extends JPanel{
	private static final long serialVersionUID = 1L;
	private  ImageIcon proH = new ImageIcon(this.getClass().getResource("images/header/prof.png"));
	JLabel prof;
	private static profPane proMenu = new profPane();
	

	public AdminProfileForm(){

		prof = new JLabel(proH);
		prof.setBounds(135, 35, 130, 53);
		prof.setVisible(true);

		proMenu.setBounds(130, 65, 617, 437);

		add(proMenu);
		add(prof);
		setLayout(null);
		setOpaque(false);
		setSize(806,628);
		setVisible(true);


	}

	public  profPane getPane(){
		return proMenu;
	}

}

class profPane extends JPanel{
	private static final long serialVersionUID = 1L;
	private JTextField userID;
	private JButton search, editP, addP, delP, viewP;
	private int uID, dUid=0;
	private JTable tableMod;
	private DefaultTableModel profileList;
	private static ViewAnyEmpProf eViewPro;
	
	Connection conn = null;
	
	//for search function to work properly
	
	public profPane() {
		//construct components
		userID = new JTextField (5);
		search = new JButton ("Search");
		viewP = new JButton ("View Own Profile");
		editP = new JButton("Edit Own Profile");
		addP = new JButton("Add Profile");
		delP = new JButton("Cancel Profile");
		eViewPro = new ViewAnyEmpProf();
		
		
		//construction of table

		String[] columnNames = {"Employee ID", "Employee Name", "Status"};
		tableMod = new JTable();
		tableMod.setModel(new javax.swing.table.DefaultTableModel(null, columnNames){
			private static final long serialVersionUID = 1L;
			public boolean isCellEditable(int rowIndex, int columnIndex) {
				return false;
			}
		});
		tableMod.getTableHeader().setReorderingAllowed(false);
		tableMod.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		profileList = (DefaultTableModel)tableMod.getModel();
		JScrollPane	scrollPane = new JScrollPane();
		scrollPane.setViewportView(tableMod);

		//adjust size and set layout
		setPreferredSize (new Dimension (617, 437));
		setLayout (null);
		setOpaque(false);
		setSize(617,437);
		setVisible(true);

		//add components
		add (userID);
		add (search);
		add (viewP);
		add(editP);
		add(addP);
		add(delP);

		add(scrollPane);

		// userID.setText(" ");

		//set component bounds (only needed by Absolute Positioning)
		userID.setBounds (20, 25, 145, 25);
		search.setBounds (170, 25, 100, 25);
		viewP.setBounds (390, 25, 140, 25);
		addP.setBounds (30, 60, 100, 25);
		delP.setBounds (150, 60, 115, 25);
		editP.setBounds (390, 60, 140, 25);

		scrollPane.setBounds(20, 105, 595, 300);

		search.setForeground(Color.WHITE);
		search.setBackground(Color.BLACK);
		viewP.setForeground(Color.WHITE);
		viewP.setBackground(Color.BLACK);
		addP.setForeground(Color.WHITE);
		addP.setBackground(Color.BLACK);
		delP.setForeground(Color.WHITE);
		delP.setBackground(Color.BLACK);
		editP.setForeground(Color.WHITE);
		editP.setBackground(Color.BLACK);

		userID.setText("");

		viewP.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				AdminViewProForm aViewOwnPro = new AdminViewProForm();
				aViewOwnPro.setVisible(true);
				aViewOwnPro.pack();
				aViewOwnPro.setLocationRelativeTo(null);
			}
		});

		editP.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				EditEmpForm aEdit = new EditEmpForm();
				aEdit.setVisible(true);
				aEdit.pack();
				aEdit.setLocationRelativeTo(null);
			}
		});

		addP.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				AddEmpForm aAdd = new AddEmpForm();
				aAdd.setVisible(true);
				aAdd.pack();
				aAdd.setLocationRelativeTo(null);
			}
		});

		delP.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				try{
					ConnectionFactory myFactory = ConnectionFactory.getFactory();
					Connection conn = myFactory.getConnection();

					PreparedStatement checkStat;
					checkStat = conn.prepareStatement("SELECT status FROM employee WHERE idemployee="+ dUid);
					ResultSet statc = checkStat.executeQuery();
					if(dUid == 0)
						JOptionPane.showMessageDialog(null, "No employee was selected. Please select the details of the employee.", "Error", JOptionPane.ERROR_MESSAGE);
					else{
						if(statc.next()){
							if(statc.getString("status").equals("Inactive"))
								JOptionPane.showMessageDialog(null, "Employee is already set to inactive", "Error", JOptionPane.ERROR_MESSAGE);
							else
							{
								DelEmpForm aDel = new DelEmpForm();
								aDel.setUID(dUid);
								aDel.setVisible(true);
								aDel.pack();
								aDel.setLocationRelativeTo(null);
							}
						}
						conn.close();
					}
				}catch(Exception ex){
					ex.printStackTrace();
				}
			}
		});
			//input method request
		userID.addKeyListener(new KeyListener(){

			public void keyTyped(KeyEvent e) {}
			public void keyPressed(KeyEvent e) {}
			public void keyReleased(KeyEvent e) {
				try{
					//userID.setText("");
				
				ConnectionFactory myFactory = ConnectionFactory.getFactory();
				Connection conn = myFactory.getConnection();

				Statement stat = conn.createStatement();

				String[] names = null;
				String uName = getUserName();
				String name1, name2, name3, name4, name5;
				ResultSet res = null;
				
					names = uName.split(" ",0);
					name1 = names[0];
					if (name1.contains(","))
						name1 = name1.split(",")[0];
					if(names.length==1)
	//search for both first name or last name
						res = stat.executeQuery("SELECT concat(firstName, ' ', middleInitial, ' ', lastName) as 'Full Name',"+
								"idemployee as 'ID', status as 'Status'from bernalcompany.employee e where firstName like '"+name1+"%' or lastName like'"+name1+"%'"); 
					else if (names.length==2)	{
	//search if (firstName lastName) or (lastName firstName) or (two firstNames) or (two lastNames) or (firstName middleInitial)
						name2 = names[1];
						if (name1.contains(","))
							name1 = name1.split(",")[0];
						res = stat.executeQuery("SELECT concat(firstName, ' ', middleInitial, ' ', lastName) as 'Full Name',"+ 
							"idemployee as 'ID', status as 'Status'from bernalcompany.employee e where (firstName like '"+name1+"%'and lastName like '"+name2+"%')"+
							" or (lastName like '"+name1+"%'and firstName like '"+name2+"%') or (firstName like '"+name1.concat(" ").concat(name2)+"%')"+"or (lastName like '"+name1.concat(" ").concat(name2)+"%')"+
							" or (firstName like '"+name1+"%' and middleInitial='"+name2+"')");
					} else if (names.length==3) { 
	//search if (firstName middleInitial lastName) or (lastName firstName middleInitial) or (firstName1 firstName2 middleInitial) or (firstname1 firstName2 lastName)or (firstName lastName1 lastName2) or (lastName1 lastName2 firstName) or (lastName firstname1 firstName2)
						name2 = names[1];
						name3 = names[2];
						if (name1.contains(","))
							name1 = name1.split(",")[0];
						else if (name2.contains(","))
								name2 = name2.split(",")[0];
						res = stat.executeQuery("SELECT concat(firstName, ' ', middleInitial, ' ', lastName) as 'Full Name',idemployee as 'ID', status as 'Status'from bernalcompany.employee e"+
								" where (firstName like '"+name1+"%' and middleInitial ='"+name2+"' and lastName like '"+name3+"%')"+
								" or (lastName like '"+name1+"%'and firstName like '"+name2+"%' and middleInitial='"+name3+"')"+
								" or (firstName like '"+name1.concat(" ").concat(name2)+"%' and middleInitial='"+name3+"') or (firstName like '"+name1.concat(" ").concat(name2)+"%' and lastName like '"+name3+"%') or (firstName like '"+name1+"%' and lastName like '"+name2.concat(" ").concat(name3)+"%')"+
								" or (lastName like '"+name1.concat(" ").concat(name2)+"%' and firstName like '"+name3+"%') or (lastName like '"+name1+"%' and firstName like '"+name2.concat(" ").concat(name3)+"%')");
					} else if (names.length==4) { 
	//search if (firstName1 firstName2 middleInitial lastName) or (firstName middleInitial lastName1 lastName2) or (firstName1 firstName2 lastName1 lastName2) or (lastName1 lastName2 firstName1 firstName2)or (firstName lastName1 lastName2) or (lastName1 lastName2 firstName) or (lastName firstname1 firstName2)
						name2 = names[1];
						name3 = names[2];
						name4 = names[3];
						if (name1.contains(","))
							name1 = name1.split(",")[0];
						else if (name2.contains(","))
								name2 = name2.split(",")[0];
						res = stat.executeQuery("SELECT concat(firstName, ' ', middleInitial, ' ', lastName) as 'Full Name',idemployee as 'ID', status as 'Status'from bernalcompany.employee e"+
								" where (firstName like '"+name1.concat(" ").concat(name2)+"%' and middleInitial ='"+name3+"' and lastName like '"+name4+"%') or (firstName like '"+name1+"%' and middleInitial ='"+name2+"' and lastName like '"+name3.concat(" ").concat(name4)+"%')"+
								" or (firstName like '"+name1.concat(" ").concat(name2)+"%' and lastName like '"+name3.concat(" ").concat(name4)+"%') or (lastName like '"+name1.concat(" ").concat(name2)+"%' and firstName like '"+name3.concat(" ").concat(name4)+"%')"+
								" or (lastName like '"+name1.concat(" ").concat(name2)+"%' and firstName like '"+name3+"%' and middleInitial='"+name4+"') or (lastName like '"+name1+"%' and firstName like '"+name2.concat(" ").concat(name3)+"%' and middleInitial='"+name4+"')");
					} else { 
	//search if (firstName1 firstName2 middleInitial lastName1 lastName2) or (lastName1 lastName2 firstName1 firstName2 middleInitial)
						name2 = names[1];
						name3 = names[2];
						name4 = names[3];
						name5 = names[4];
						if (name2.contains(","))
							name2 = name2.split(",")[0];
						res = stat.executeQuery("SELECT concat(firstName, ' ', middleInitial, ' ', lastName) as 'Full Name',idemployee as 'ID', status as 'Status'from bernalcompany.employee e"+
								" where (firstName like '"+name1.concat(" ").concat(name2)+"%' and middleInitial ='"+name3+"' and lastName like '"+name4.concat(" ").concat(name5)+"%')"+
								" or (lastName like '"+name1.concat(" ").concat(name2)+"%' and middleInitial ='"+name3+"' and firstName like '"+name4.concat(" ").concat(name5)+"%')");
					}
					
						profileList.getDataVector().removeAllElements();
						tableMod.setAutoCreateRowSorter(true);

						while(res.next()){
							profileList.addRow(new Object[]{ res.getInt("ID"), res.getString("Full Name"), res.getString("Status")});
							profileList.fireTableDataChanged();
						}

						conn.close();
			

				

			}catch(Exception ex){
				ex.printStackTrace();
			}


			}
			
		});
			search.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){

				try{


					if ( getUserName().length() == 0 )
						JOptionPane.showMessageDialog(null, "No name was entered. Please try again.", "Error", JOptionPane.ERROR_MESSAGE);

					else {

						String uName = getUserName();
						//userID.setText("");

						if ( getCheckSpace() == 0)
							JOptionPane.showMessageDialog(null, "Enter first name and last name of employee.");

						else if ( getCheckSpace() == 1 ) {
						
							ConnectionFactory myFactory = ConnectionFactory.getFactory();
							Connection conn = myFactory.getConnection();

							Statement stat = conn.createStatement();

							String[] names = null;
							uName = getUserName();
							String name1, name2, name3, name4, name5;
							ResultSet res = null;
							
								names = uName.split(" ",0);
								name1 = names[0];
								if (name1.contains(","))
									name1 = name1.split(",")[0];
								if(names.length==1)
				//search for both first name or last name
									res = stat.executeQuery("SELECT idemployee from bernalcompany.employee e where firstName like '"+name1+"%' or lastName like'"+name1+"%'"); 
								else if (names.length==2)	{
				//search if (firstName lastName) or (lastName firstName) or (two firstNames) or (two lastNames) or (firstName middleInitial)
									name2 = names[1];
									if (name1.contains(","))
										name1 = name1.split(",")[0];
									res = stat.executeQuery("SELECT idemployee from bernalcompany.employee e where (firstName like '"+name1+"%'and lastName like '"+name2+"%')"+
										" or (lastName like '"+name1+"%'and firstName like '"+name2+"%') or (firstName like '"+name1.concat(" ").concat(name2)+"%')"+"or (lastName like '"+name1.concat(" ").concat(name2)+"%')"+
										" or (firstName like '"+name1+"%' and middleInitial='"+name2+"')");
								} else if (names.length==3) { 
				//search if (firstName middleInitial lastName) or (lastName firstName middleInitial) or (firstName1 firstName2 middleInitial) or (firstname1 firstName2 lastName)or (firstName lastName1 lastName2) or (lastName1 lastName2 firstName) or (lastName firstname1 firstName2)
									name2 = names[1];
									name3 = names[2];
									if (name1.contains(","))
										name1 = name1.split(",")[0];
									else if (name2.contains(","))
											name2 = name2.split(",")[0];
									res = stat.executeQuery("SELECT idemployee from bernalcompany.employee e"+
											" where (firstName like '"+name1+"%' and middleInitial ='"+name2+"' and lastName like '"+name3+"%')"+
											" or (lastName like '"+name1+"%'and firstName like '"+name2+"%' and middleInitial='"+name3+"')"+
											" or (firstName like '"+name1.concat(" ").concat(name2)+"%' and middleInitial='"+name3+"') or (firstName like '"+name1.concat(" ").concat(name2)+"%' and lastName like '"+name3+"%') or (firstName like '"+name1+"%' and lastName like '"+name2.concat(" ").concat(name3)+"%')"+
											" or (lastName like '"+name1.concat(" ").concat(name2)+"%' and firstName like '"+name3+"%') or (lastName like '"+name1+"%' and firstName like '"+name2.concat(" ").concat(name3)+"%')");
								} else if (names.length==4) { 
				//search if (firstName1 firstName2 middleInitial lastName) or (firstName middleInitial lastName1 lastName2) or (firstName1 firstName2 lastName1 lastName2) or (lastName1 lastName2 firstName1 firstName2)or (firstName lastName1 lastName2) or (lastName1 lastName2 firstName) or (lastName firstname1 firstName2)
									name2 = names[1];
									name3 = names[2];
									name4 = names[3];
									if (name1.contains(","))
										name1 = name1.split(",")[0];
									else if (name2.contains(","))
											name2 = name2.split(",")[0];
									res = stat.executeQuery("SELECT idemployee from bernalcompany.employee e"+
											" where (firstName like '"+name1.concat(" ").concat(name2)+"%' and middleInitial ='"+name3+"' and lastName like '"+name4+"%') or (firstName like '"+name1+"%' and middleInitial ='"+name2+"' and lastName like '"+name3.concat(" ").concat(name4)+"%')"+
											" or (firstName like '"+name1.concat(" ").concat(name2)+"%' and lastName like '"+name3.concat(" ").concat(name4)+"%') or (lastName like '"+name1.concat(" ").concat(name2)+"%' and firstName like '"+name3.concat(" ").concat(name4)+"%')"+
											" or (lastName like '"+name1.concat(" ").concat(name2)+"%' and firstName like '"+name3+"%' and middleInitial='"+name4+"') or (lastName like '"+name1+"%' and firstName like '"+name2.concat(" ").concat(name3)+"%' and middleInitial='"+name4+"')");
								} else { 
				//search if (firstName1 firstName2 middleInitial lastName1 lastName2) or (lastName1 lastName2 firstName1 firstName2 middleInitial)
									name2 = names[1];
									name3 = names[2];
									name4 = names[3];
									name5 = names[4];
									if (name2.contains(","))
										name2 = name2.split(",")[0];
									res = stat.executeQuery("SELECT idemployee from bernalcompany.employee e"+
											" where (firstName like '"+name1.concat(" ").concat(name2)+"%' and middleInitial ='"+name3+"' and lastName like '"+name4.concat(" ").concat(name5)+"%')"+
											" or (lastName like '"+name1.concat(" ").concat(name2)+"%' and middleInitial ='"+name3+"' and firstName like '"+name4.concat(" ").concat(name5)+"%')");
								}
							if (res.next()){

								userID.setText("");
								uID = res.getInt("idemployee");
								userID.setText("");
								viEmpProfPane.setUID(uID);
								eViewPro.getPane().searchProf();
								eViewPro.setVisible(true);
								eViewPro.pack();
								eViewPro.setLocationRelativeTo(null);
							}
							else
								JOptionPane.showMessageDialog(null, "Employee not in the database.");

						}

					}

				}catch(Exception ex){
					ex.printStackTrace();
				}
			}
		}
		);  


		tableMod.addMouseListener(new MouseAdapter()   
		{  
			public void mouseClicked(MouseEvent evt)  
			{  
				int row = tableMod.getSelectedRow();  
				dUid = Integer.parseInt((tableMod.getModel().getValueAt(row, 0)).toString());  
			}  
		});  

	}

	public String getUserName(){
		String userName = userID.getText().trim();
		return userName;	    	
	}

	public int getCheckSpace(){

		String uName = userID.getText();

		char[] unameArray = uName.toCharArray();

		int i = 0;
		int lenSpace = uName.length();

		while ( lenSpace > 0)
		{ 	char c = unameArray[i];

		if ( c == ' '){
			//may space!
			return 1;
		}
		else
			lenSpace--;
		i++;
		}
		return 0;
	}

	public void listUpdate(){

		try
		{
			ConnectionFactory myFactory = ConnectionFactory.getFactory();
			Connection conn = myFactory.getConnection();
			PreparedStatement stat = (PreparedStatement) conn.prepareStatement("SELECT concat(firstName, ' ', middleInitial, ' ', lastName) as 'Full Name',"+
			"idemployee as 'ID', status as 'Status'from bernalcompany.employee e order by idemployee, status"); 
			ResultSet res = stat.executeQuery();

			profileList.getDataVector().removeAllElements();
			tableMod.setAutoCreateRowSorter(true);

			while(res.next()){
				profileList.addRow(new Object[]{ res.getInt("ID"), res.getString("Full Name"), res.getString("Status")});
				profileList.fireTableDataChanged();
			}

			conn.close();

		}catch(Exception ex){
			ex.printStackTrace();
		}

	}
}